import React, { useState, useEffect } from 'react';
import { Form, Space, Button, Row, Col, message, Modal } from 'antd';
import { CmdbContent, CmdbHeader } from '@/components';
import BaseInfoSection from './components/BaseInfoSection';
import DeploymentTopologySection from './components/DeploymentTopologySection';
import CloudZoneSection from './components/CloudZoneSection';
import BusinessSection from './components/BusinessSection';
import TemplateSelectionModal from './components/TemplateSelectionModal';
import { useHistory, useLocation } from 'react-router-dom';
import '../../index.less';

function TemplateCloudtAdd () {
  const [form] = Form.useForm();
  const history = useHistory();
  const location = useLocation();
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedTemplates, setSelectedTemplates] = useState([]);
  const [province, setProvince] = useState([]);
  const [cloudZones, setCloudZones] = useState({});
  const [selectedTag, setSelectedTag] = useState('对象存储业务');
  const [deployedTemplates, setDeployedTemplates] = useState([]);
  const [cancelVisible, setCancelVisible] = useState(false);
  const [deployTopologyError, setDeployTopologyError] = useState('');

  // 模拟模板数据
  const [templateList] = useState([
    {
      key: '1',
      templateName: '模块模板1',
      templateId: '32123',
      description: '这是模块模板1',
      createTime: '2023-06-01 10:30:00',
      clusterTemplates: [
        { key: 'cluster1', name: '集群模板1', moduleTemplates: [{ key: 'module1', name: '模块模板1' }] }
      ]
    },
    {
      key: '2',
      templateName: '模块模板2',
      templateId: '32124',
      description: '这是模块模板2',
      createTime: '2023-05-28 15:45:00',
      clusterTemplates: [
        { key: 'cluster2', name: '集群模板2', moduleTemplates: [{ key: 'module2', name: '模块模板2' }] }
      ]
    },
    {
      key: '3',
      templateName: '对象存储业务模板',
      templateId: '32125',
      description: '这是对象存储业务模板',
      createTime: '2023-05-20 09:15:00',
      clusterTemplates: [
        { key: 'cluster3', name: '集群模板3', moduleTemplates: [{ key: 'module3', name: '模块模板3' }] }
      ]
    },
  ]);

  useEffect(() => {
    const { state } = location;
    if (state?.isEdit && state?.task) {
      // 编辑模式下填充数据
      const formValues = {
        templateName: state.task.templateName,
        templateDescription: state.task.templateDescription,
        version: state.task.version,
        tag: state.task.tag || '对象存储业务'
      };
      form.setFieldsValue(formValues);
      setDeployedTemplates(state.task.deployedTemplates || []);
      setProvince(state.task.province || []);
      setCloudZones(state.task.cloudZones || {});
      setSelectedTag(state.task.tag || '对象存储业务');
    }
  }, [location, form]);

  // 添加业务模板
  const handleAddProcess = () => {
    setModalVisible(true);
    setSelectedTemplates([]);
  };

  // 确认选择模板
  const handleConfirmSelection = () => {
    if (selectedTemplates.length === 0) {
      message.warning('请至少选择一个模板');
      return;
    }

    const newTemplates = selectedTemplates.map(key =>
      templateList.find(template => template.key === key)
    ).filter(Boolean);

    setDeployedTemplates([...deployedTemplates, ...newTemplates]);
    setDeployTopologyError('');
    setModalVisible(false);
    message.success('添加成功');
  };

  // 移除模板
  const removeTemplate = (key) => {
    Modal.confirm({
      title: '确认删除该模板?',
      content: '删除后该模板将从部署拓扑中移除',
      onOk () {
        const newTemplates = deployedTemplates.filter(template => template.key !== key);
        setDeployedTemplates(newTemplates);
        if (newTemplates.length === 0) {
          setDeployTopologyError('最少添加1个业务模版');
        }
        message.success('删除成功');
      }
    });
  };

  // 保存
  const handleSave = async (values) => {
    try {
      // 手动验证部署拓扑
      if (deployedTemplates.length === 0) {
        setDeployTopologyError('最少添加1个业务模版');
        throw new Error('请添加部署拓扑');
      }

      // 手动验证省份
      if (province.length === 0) {
        message.error('请选择至少一个省份');
        throw new Error('请选择省份');
      }

      // 手动验证业务
      if (!selectedTag) {
        message.error('请选择适用业务');
        throw new Error('请选择业务');
      }

      // 收集所有数据
      const formData = {
        ...values,
        deployedTemplates,
        province,
        cloudZones,
        tag: selectedTag
      };

      console.log("完整表单数据:", formData);

      // 模拟生成数据
      const newTask = {
        id: location.state?.task?.id || `T${Date.now().toString().slice(-7)}`,
        templateName: values.templateName.substring(0, 20),
        templateDescription: values.templateDescription ? values.templateDescription.substring(0, 100) : '',
        version: values.version.substring(0, 30),
        author: '当前用户',
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString(),
        status: 'check-success',
        deployedTemplates: deployedTemplates,
        province: province,
        cloudZones: cloudZones,
        tag: selectedTag
      };

      // 这里应该是API调用，这里用localStorage模拟
      const existingTasks = JSON.parse(localStorage.getItem('templateTasks') || '[]');

      if (location.state?.task?.id) {
        const index = existingTasks.findIndex(task => task.id === location.state.task.id);
        if (index !== -1) {
          existingTasks[index] = newTask;
        } else {
          existingTasks.push(newTask);
        }
        message.success('更新成功');
      } else {
        existingTasks.push(newTask);
        message.success('保存成功');
      }

      localStorage.setItem('templateTasks', JSON.stringify(existingTasks));
      history.push('/template/all-cloud');

    } catch (errorInfo) {
      console.log("保存失败:", errorInfo);
    }
  };

  // 取消
  const handleCancel = () => {
    setCancelVisible(true);
  };

  const confirmCancel = () => {
    setCancelVisible(false);
    history.goBack();
  };

  const closeCancelModal = () => {
    setCancelVisible(false);
  };

  return (
    <CmdbContent>
      <div className="header-bar">
        <Button type='text' onClick={() => history.goBack()}>
          返回
        </Button>
        <CmdbHeader title={location.state?.task?.id ? "编辑云区域模版" : "新建云区域模版"} />
        <div></div>
      </div>

      <div className="template-cloudt-add">
        <Form
          form={form}
          layout="vertical"
          initialValues={{ version: '1.0', tag: '对象存储业务' }}
          onFinish={handleSave}
        >
          <BaseInfoSection form={form} />

          <DeploymentTopologySection
            deployedTemplates={deployedTemplates}
            onAddProcess={handleAddProcess}
            removeTemplate={removeTemplate}
            error={deployTopologyError}
          />

          <CloudZoneSection
            province={province}
            cloudZones={cloudZones}
            onProvinceChange={setProvince}
            onCloudZonesChange={setCloudZones}
          />

          <BusinessSection
            selectedTag={selectedTag}
            onTagChange={setSelectedTag}
            form={form}
          />

          <div className="form-footer">
            <Space>
              <Button onClick={handleCancel}>取消</Button>
              <Button type="primary" htmlType="submit">保存</Button>
            </Space>
          </div>
        </Form>
      </div>

      <TemplateSelectionModal
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        onConfirm={handleConfirmSelection}
        selectedTemplates={selectedTemplates}
        onSelectionChange={setSelectedTemplates}
        templateList={templateList}
      />

      <Modal
        title="提示"
        visible={cancelVisible}
        onOk={confirmCancel}
        onCancel={closeCancelModal}
        okText="确认"
        cancelText="取消"
      >
        确认取消本次操作？
      </Modal>
    </CmdbContent>
  );
}

export default TemplateCloudtAdd;